# encoding: utf-8
from .. import db
from datetime import datetime

class Category(db.Model):
    __tablename__ = "categories"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), nullable=False)
    is_valide = db.Column(db.Boolean, default=True)

    articles = db.relationship("Article", backref="category", lazy="dynamic")
    created_time = db.Column(db.DateTime)

    def __init__(self, name):
        self.name = name
        self.created_time = datetime.now()

    # 添加
    def add(self):
        db.session.add(self)
        db.session.commit()

    # 判断分类名称是否存在
    @classmethod
    def is_name_existed(cls, name):
        result = cls.query.filter_by(is_valide=True, name=name).first()
        if result:
            return True
        else:
            return False

    # 获取分类列表
    @classmethod
    def queryAll(cls):
        rows = cls.query.filter_by(is_valide=True).all()
        result = []
        for row in rows:
            article_count = row.articles.count()
            result.append({
                "id": row.id,
                "name": row.name,
                "article_count": article_count,
                "created_time": row.created_time
            })
        print(result)
        return result

    # 获取分类列表以元组
    @classmethod
    def queryAllbyTuple(cls):
        rows = cls.query.filter_by(is_valide=True).all()
        result = []
        for row in rows:
            result.append((row.id, row.name))
        return result

    # 按照id删除
    @classmethod
    def deleteById(cls, id):
        category = cls.query.filter_by(is_valide=True, id=id).first()
        if category:
            category.is_valide = False
            db.session.add(category)
            db.session.commit()